<template>
  <div class="order-detail-page">
    <div class="container py-4">
      <!-- 加载状态 -->
      <div v-if="loading" class="text-center py-5">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2 text-muted">正在加载订单详情...</p>
      </div>

      <!-- 订单不存在 -->
      <div v-else-if="!order" class="text-center py-5">
        <i class="fas fa-exclamation-triangle fa-4x text-warning mb-3"></i>
        <h4>订单不存在</h4>
        <p class="text-muted">该订单可能已被删除或不存在</p>
        <button class="btn btn-primary" @click="goBack">返回订单列表</button>
      </div>

      <!-- 订单详情内容 -->
      <div v-else>

        <!-- 订单基本信息 -->
        <div class="order-info-card card mb-4">
          <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>订单信息</h5>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-6">
                <div class="info-item mb-3">
                  <label class="text-muted">订单编号</label>
                  <div class="fw-bold order-no">{{ order.orderNo }}</div>
                </div>
                <div class="info-item mb-3">
                  <label class="text-muted">下单时间</label>
                  <div>{{ formatDate(order.createdTime) }}</div>
                </div>
                <div class="info-item mb-3" v-if="order.payTime">
                  <label class="text-muted">支付时间</label>
                  <div>{{ formatDate(order.payTime) }}</div>
                </div>
              </div>
              <div class="col-md-6">
                <div class="info-item mb-3">
                  <label class="text-muted">支付方式</label>
                  <div>{{ order.payType || '未支付' }}</div>
                </div>
                <div class="info-item mb-3" v-if="order.updateTime">
                  <label class="text-muted">更新时间</label>
                  <div>{{ formatDate(order.updateTime) }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="order-items-card card mb-4">
          <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-shopping-cart me-2"></i>商品信息</h5>
          </div>
          <div class="card-body">
            <!-- 加载状态 -->
            <div v-if="itemsLoading" class="text-center py-4">
              <div class="spinner-border spinner-border-sm text-primary me-2" role="status"></div>
              <span class="text-muted">正在加载商品信息...</span>
            </div>
            
            <!-- 订单项列表 -->
            <div v-else-if="orderItems.length > 0">
              <div 
                class="order-item-row d-flex align-items-center py-3 border-bottom"
                v-for="(item, index) in orderItems" 
                :key="item.id || index"
              >
                <div class="item-image me-3">
                  <img 
                    :src="item.goodPic || placeholderImage(80, 80)" 
                    :alt="item.goodName"
                    class="rounded"
                    style="width: 80px; height: 80px; object-fit: cover;"
                  />
                </div>
                <div class="item-info flex-grow-1">
                  <h6 class="item-name mb-1">{{ item.goodName }}</h6>
                  <p class="item-desc text-muted small mb-2">{{ item.goodDesc || '暂无描述' }}</p>
                  <div class="item-meta">
                    <span class="item-price text-danger fw-bold">{{ formatPrice(item.dealPrice) }}</span>
                    <span class="item-quantity text-muted ms-3">x{{ item.count }}</span>
                  </div>
                </div>
                <div class="item-total text-end">
                  <div class="fw-bold">{{ formatPrice(item.dealPrice * item.count) }}</div>
                </div>
              </div>
            </div>
            
            <!-- 无商品信息 -->
            <div v-else class="text-center py-4 text-muted">
              <i class="fas fa-box-open fa-2x mb-2"></i>
              <p class="mb-0">暂无商品信息</p>
            </div>
          </div>
        </div>

        <!-- 收货地址 -->
        <div class="shipping-info-card card mb-4">
          <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-map-marker-alt me-2"></i>收货信息</h5>
          </div>
          <div class="card-body">
            <div class="address-info">
              <div class="recipient-info mb-2">
                <span class="recipient-name fw-bold">{{ order.receiverName || '未设置' }}</span>
                <span class="recipient-phone text-muted ms-3">{{ order.receiverPhone || '未设置' }}</span>
              </div>
              <div class="address-detail text-muted">
                {{ order.receiverAddrDetail || '未设置收货地址' }}
              </div>
            </div>
          </div>
        </div>

        <!-- 费用明细 -->
        <div class="payment-info-card card mb-4">
          <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-calculator me-2"></i>费用明细</h5>
          </div>
          <div class="card-body">
            <div class="payment-details">
              <div class="d-flex justify-content-between mb-2">
                <span>商品总价</span>
                <span>{{ orderItems.length > 0 ? formatPrice(calculateItemsTotal()) : formatPrice(order.totalPay) }}</span>
              </div>
              <div class="d-flex justify-content-between mb-2">
                <span>运费</span>
                <span>¥0.00</span>
              </div>
              <div class="d-flex justify-content-between mb-2">
                <span>优惠金额</span>
                <span class="text-success">-¥0.00</span>
              </div>
              <hr>
              <div class="d-flex justify-content-between fw-bold h5 text-danger">
                <span>实付金额</span>
                <span>{{ formatPrice(order.totalPay) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 订单备注 -->
        <div v-if="order.orderComment" class="order-comment-card card mb-4">
          <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-comment me-2"></i>订单备注</h5>
          </div>
          <div class="card-body">
            <p class="mb-0">{{ order.orderComment }}</p>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="order-actions-card card">
          <div class="card-body text-center">
            <div class="btn-group-custom">
              <button 
                v-if="order.status === 'pending'"
                class="btn btn-primary me-2"
                @click="payOrder"
              >
                <i class="fas fa-credit-card me-1"></i>
                立即付款
              </button>
              <button 
                v-if="order.status === 'shipped'"
                class="btn btn-success me-2"
                @click="confirmReceipt"
              >
                <i class="fas fa-check me-1"></i>
                确认收货
              </button>
              <button 
                v-if="order.status === 'pending'"
                class="btn btn-outline-danger me-2"
                @click="cancelOrder"
              >
                <i class="fas fa-times me-1"></i>
                取消订单
              </button>
              <button 
                class="btn btn-outline-secondary"
                @click="contactService"
              >
                <i class="fas fa-headset me-1"></i>
                联系客服
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message } from '@/utils/message'

// 导入API
import { getOrderDetail, updateOrderStatus, getOrderItems } from '@/api/order'
import type { Order, OrderItem } from '@/types/order'

const route = useRoute()
const router = useRouter()

// 页面状态
const loading = ref(false)
const order = ref<Order | null>(null)
const orderItems = ref<OrderItem[]>([])
const itemsLoading = ref(false)

// 占位符图片生成函数
const placeholderImage = (width: number, height: number) => {
  return `https://picsum.photos/${width}/${height}?random=${Math.floor(Math.random() * 1000)}`
}

// 获取订单详情
const fetchOrderDetail = async () => {
  const orderId = route.params.id as string
  if (!orderId || isNaN(Number(orderId))) {
    Message.error('无效的订单ID')
    router.push('/orders')
    return
  }

  loading.value = true
  try {
    const response = await getOrderDetail(Number(orderId))
    order.value = response.data
    
    // 获取订单项信息
    await fetchOrderItems(Number(orderId))
  } catch (error: any) {
    console.error('获取订单详情失败:', error)
    Message.error('获取订单详情失败')
    order.value = null
  } finally {
    loading.value = false
  }
}

// 获取订单项列表
const fetchOrderItems = async (orderId: number) => {
  itemsLoading.value = true
  try {
    const response = await getOrderItems(orderId)
    orderItems.value = response.data || []
  } catch (error: any) {
    console.error('获取订单项失败:', error)
    orderItems.value = []
  } finally {
    itemsLoading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '未设置'
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化价格
const formatPrice = (price: number) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(price)
}

// 计算订单项总价
const calculateItemsTotal = () => {
  return orderItems.value.reduce((total, item) => {
    return total + (item.dealPrice * item.count)
  }, 0)
}

// 获取状态图标
const getStatusIcon = (status: string) => {
  const statusIcons = {
    'pending': 'fas fa-clock text-warning',
    'paid': 'fas fa-credit-card text-info',
    'shipped': 'fas fa-truck text-primary',
    'completed': 'fas fa-check-circle text-success',
    'cancelled': 'fas fa-times-circle text-secondary'
  }
  return statusIcons[status as keyof typeof statusIcons] || 'fas fa-question-circle text-secondary'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusTexts = {
    'pending': '待付款',
    'paid': '待发货',
    'shipped': '待收货',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusTexts[status as keyof typeof statusTexts] || '未知状态'
}

// 获取状态描述
const getStatusDescription = (status: string) => {
  const statusDescriptions = {
    'pending': '请在24小时内完成支付，超时订单将自动取消',
    'paid': '您的订单正在准备发货中',
    'shipped': '您的订单已发货，请注意查收',
    'completed': '感谢您的购买，期待您的再次光临',
    'cancelled': '订单已取消'
  }
  return statusDescriptions[status as keyof typeof statusDescriptions] || ''
}

// 支付订单
const payOrder = () => {
  Message.info('支付功能待实现')
}

// 确认收货
const confirmReceipt = async () => {
  if (!order.value) return
  
  try {
    await updateOrderStatus(order.value.id, 'completed')
    Message.success('确认收货成功')
    await fetchOrderDetail() // 刷新订单信息
  } catch (error) {
    console.error('确认收货失败:', error)
    Message.error('确认收货失败')
  }
}

// 取消订单
const cancelOrder = async () => {
  if (!order.value) return
  
  try {
    await updateOrderStatus(order.value.id, 'cancelled')
    Message.success('订单已取消')
    await fetchOrderDetail() // 刷新订单信息
  } catch (error) {
    console.error('取消订单失败:', error)
    Message.error('取消订单失败')
  }
}

// 联系客服
const contactService = () => {
  Message.info('客服功能待实现')
}

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-page {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.page-header h2 {
  color: #333;
  font-weight: 600;
}

.order-status-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
}

.status-icon {
  font-size: 3rem;
}

.order-no {
  font-family: 'Courier New', monospace;
  font-size: 1.1rem;
}

.info-item label {
  font-size: 0.9rem;
  margin-bottom: 4px;
  display: block;
}

.order-item-row:last-child {
  border-bottom: none !important;
}

.item-name {
  color: #333;
  margin-bottom: 4px;
}

.item-desc {
  line-height: 1.3;
}

.address-info {
  padding: 10px 0;
}

.recipient-name {
  font-size: 1.1rem;
}

.payment-details {
  max-width: 400px;
  margin-left: auto;
}

.btn-group-custom .btn {
  margin: 5px;
}

.card {
  border: none;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
}

.card-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  padding: 15px 20px;
}

.card-header h5 {
  color: #495057;
  font-weight: 600;
}

.card-body {
  padding: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }
  
  .order-item-row {
    flex-direction: column;
    align-items: flex-start !important;
  }
  
  .item-image {
    margin-bottom: 15px;
  }
  
  .item-total {
    margin-top: 10px;
    text-align: left !important;
  }
  
  .btn-group-custom {
    text-align: center;
  }
  
  .btn-group-custom .btn {
    margin: 3px;
    font-size: 0.9rem;
  }
  
  .payment-details {
    max-width: 100%;
  }
}
</style> 